﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ThreeByte.ActiveDeck.Config;
using ThreeByte.ActiveDeck.Service;
using System.Xml.Linq;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;
using ThreeByte.ActiveDeck.Data;
using ThreeByte.Media;
using System.IO;
using ThreeByte.ActiveDeck.AddIn.Content.UserResponse;
using ThreeByte.ActiveDeck.Data.UserResponse;
using log4net;
using ThreeByte.ActiveDeck.Controls.UserResponse;
using System.Diagnostics;
using ThreeByte.ActiveDeck.AddIn.Config;
using ThreeByte.ActiveDeck.Content;


namespace ThreeByte.ActiveDeck.Controls
{
    /// <summary>
    /// Interaction logic for OperatorMonitorControl.xaml
    /// </summary>
    public partial class OperatorMonitorControl : UserControl
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(OperatorMonitorControl));

        private PresentationMonitor PresentationMonitor;
        public CoreConfig Config;

        public OperatorMonitorControl(PresentationMonitor presentationMonitor) {
            InitializeComponent();
            PresentationMonitor = presentationMonitor;
            DataContext = PresentationMonitor;

            Config = PresentationMonitor.Config;
            ShowCheckBox.DataContext = Config.Environment;

            DebugHyperLink.NavigateUri = new Uri(string.Format("{0}/console/#/Inspect/{1}", ServiceConfiguration.SERVICE_HOST, Config.ID));
            DebugHyperLink.ToolTip = DebugHyperLink.NavigateUri.AbsoluteUri;

            PresentationMonitor.SlidePreviewChanged += new EventHandler<SlideConfigEventArgs>(PresentationMonitor_SlidePreviewChanged);
            PresentationMonitor.UserResponsePreviewChanged += new EventHandler<UserResponseConfigEventArgs>(PresentationMonitor_UserResponsePreviewChanged);  
        }


        private void Hyperlink_Click(object sender, RoutedEventArgs e) {
            Hyperlink link = (Hyperlink)sender;
            try {
                string webAddress = link.NavigateUri.AbsoluteUri;
                ProcessStartInfo ps = new ProcessStartInfo(webAddress);
                ps.UseShellExecute = true;
                Process.Start(ps);
            } catch (Exception ex) {
                log.Error("Could not open address", ex);
            }
        }

        private void PresentationMonitor_SlidePreviewChanged(object sender, SlideConfigEventArgs e) {
            Dispatcher.Invoke(new Action<SlideConfig>(UpdateiPadPreview), e.SlideConfig);
        }

        private void UpdateiPadPreview(SlideConfig slideConfig) {
            PreviewRoot.Content = null;

            if(slideConfig == null) {
                PreviewGrid.Visibility = Visibility.Hidden;
                return;
            }
            PreviewGrid.Visibility = Visibility.Visible;

            PageConfig firstPage = slideConfig.Pages.First();
            firstPage.Refresh();
            PreviewRoot.Content = PagePreviewFactory.Create(firstPage);
        }

        private void PresentationMonitor_UserResponsePreviewChanged(object sender, UserResponseConfigEventArgs e) {
            log.DebugFormat("Handling UserResponsePreviewChanged: {0}", e.Updater);
            if(e.Updater == null) {
                //Clear the user response graphics
                Dispatcher.Invoke(new Action<UserResponseFeedbackUpdater>(UpdateUserResponseData), new object[]{null});
                return;
            }
            e.Updater.DataUpdated += new EventHandler(Updater_DataUpdated);
        }

        void Updater_DataUpdated(object sender, EventArgs e) {
            UserResponseFeedbackUpdater updater = (UserResponseFeedbackUpdater)sender;
            Dispatcher.Invoke(new Action<UserResponseFeedbackUpdater>(UpdateUserResponseData), updater);
        }

        private void UpdateUserResponseData(UserResponseFeedbackUpdater updater) {
            log.Debug("UpdateUserResponseData");
            if(updater == null) {
                UserResponseGrid.Visibility = Visibility.Hidden;
                return;
            }
            UserResponseGrid.Visibility = Visibility.Visible;

            //Parse the user data
            XElement userDataNode = updater.CurrentUserData;
            if(userDataNode == null) {
                log.Info("No User Data to read");
                TotalUserSubmissionTextBlock.Text = string.Format("{0}", 0);
                return;
            }

            try {
                string type = userDataNode.Attribute("Type").Value;
                AggregateUserData userData = AggregateUserData.ParseXml(userDataNode);

                if(userData == null) {
                    log.Warn("No User data to update");
                } else {
                    TotalUserSubmissionTextBlock.Text = string.Format("{0}", userData.TotalResponses);
                }

            } catch(Exception ex) {
                log.Warn("Problem parsing userdata", ex);
            }


        }

    }
}
